package com.liu.udpChat;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class TalkSend implements Runnable{
    private String toIp;
    private String myIp;
    private int toPort;
    private int myPort;
    DatagramSocket socket;
    InetAddress inetAddress;

    public TalkSend(String toIp, int toPort, int myPort) {
        this.toIp = toIp;
        this.toPort = toPort;
        this.myPort = myPort;
        try {
            this.socket=new DatagramSocket(myPort);
            inetAddress=InetAddress.getByName(this.toIp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        try {
            Scanner scanner=new Scanner(System.in);
            while (true) {
                String str=scanner.next();
                DatagramPacket packet = new DatagramPacket(str.getBytes(),0,str.getBytes().length,inetAddress,toPort);
                socket.send(packet);
                if (str.equals("bye")){
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            socket.close();
        }
    }
}
